<?php
/**
 * @uses 		his队列访问
 * @author 		Duan
 * @version 	1.0
 * @copyright	Yihuan	
 */
namespace Common\Model;


class PopModel 
{
	/**
	 * @uses 	his队列访问
	 * @return  void
	 */
	public static function index()
	{
		$Redis 	 	= \Common\Model\ServeModel::serveRedis(); 		//起用Redis
		$receiveKey = C('RECEIVE_KEY'); 							//执行队列的key值
		$pushKey 	= C('PUSH_KEY'); 								//推送队列的key值
		$pop 		= $Redis->lpop($receiveKey); 					//出栈
		if (!$pop) { echo 'noData to be Pop, 时间：'.time();die;} 				//没有数据输出noData
		$value 		= json_decode($pop, true); 						
		$function 	= $value['call_fun'];							
		$params 	= $value['params'];								
		if ($value['time'] >= time()) {  							//判断是否到了执行时间，如果没有重入队列
			$pushResult = $Redis->rpush($receiveKey , $pop);
			echo 'noTime , 时间：'.time().', retry：'.($pushResult ? 'true' : 'false').'params：'.$pop;
			die;
		}
		$key 		= C('KEY');  									//医院的ID值
		$timeout 	= C('TIMEOUT'); 								//超时时间
		$url 		= C('URL_API');  								//API
		$space 		= C('FOLDER_NAME'); 							//医院API目录
		$namespace 	= '\Org\Util\\'.$space.'\ApiServer'; 			//访问API
		$ApiServer 	= new $namespace($url , $key , $timeout);
		$result 	= $ApiServer->$function($params);
		if ($result['code'] == 504) { 			//如果存在504 则为网络访问
			$retryNum 	= C('RETRY_NUM'); 		//最大重试次数
			if ($retryNum <= $value['num']) { 	//如果小于等于 则说明已经完了 给402网络错误
				$value['result']= ['code' => 402 , 'errorMsg' => '网络错误'];
				$pushResult 	= $Redis->rpush($pushKey , json_encode($value , JSON_UNESCAPED_UNICODE));
				echo '504 , 时间：'.time().', params: '.$pop.' , result :'.json_encode($result ,JSON_UNESCAPED_UNICODE).' , real result : 402';
			} else { 							//否则重试
				$value['time']  = C('RETRY_TIME') + time();
				$value['num']   = $value['num'] + 1;
				$pushResult = $Redis->rpush($receiveKey , json_encode($value , JSON_UNESCAPED_UNICODE));
				echo '504 , 时间：'.time().', params: '.$pop.' , result :'.json_encode($result ,JSON_UNESCAPED_UNICODE).' , retry：'.($pushResult ? 'true' : 'false').'params：'.$pop . 'num :'.$value['num'];
			}
		} else { 	//如果200得到结果
			$value['result'] 	= json_encode($result , JSON_UNESCAPED_UNICODE);
			$Redis->rpush($pushKey , json_encode($value , JSON_UNESCAPED_UNICODE));
			echo '200 , 时间：'.time().', params: '.$pop.' , result :'.json_encode($result ,JSON_UNESCAPED_UNICODE);
		}
	}
}